package com.nstar.base.controls
{
	import mx.controls.ProgressBar;
	import mx.core.Application;
	import mx.managers.PopUpManager
	import mx.events.ResizeEvent;
	import com.nstar.base.event.RPCEvent;
	import mx.collections.ArrayCollection;
	import flash.events.Event;
	
	/**
	 * 监听组件载入数据解析完成的进度条
	 * 
	 * 在sources中配置需要等待载入的数据的组件数组，
	 * 必须确定这些组件在完成数据解析后会触发RPCEvent.DATA_PARSE_COMPLETED事件
	 * 当已配置的组件数组都完成数据解析后，模态进度条自动隐藏
	 * 
	 * Example:
	 * 首先，声明构造监听进度条
	 * #public var progressBar:ListenerProgressBar = new ListenerProgressBar();
	 * 
	 * 其次，在组件数据载入之前显示进度条，并将需要监听的组件加入sources
	 * #progressBar.show();
	 * #progressBar.sources = [area,prodSpec,returnReason,jobSpec];
	 * 
	 * 
	 * @author 李嘉陵
	 * @since 2007-05-23
	 */
	public class ListenerProgressBar extends ProgressBar
	{
		private var app:*;
		
		private var _sources:ArrayCollection;
		
		public function ListenerProgressBar()
		{
			super();
			
			this.label = "数据载入中...";
			this.height = 25;
			this.percentWidth = 100;
			this.indeterminate = true;
			this.labelPlacement = "center";
		}
		
		/**
		 * 显示进度条
		 */
		public function show() : void
		{
			if(Application.application != null) {
				app = Application.application;
				PopUpManager.addPopUp(this,app,true);
				this.x = app.width/2 - this.width/2;
				this.y = app.height/2 - this.height/2;
					
				app.addEventListener(ResizeEvent.RESIZE,resizeHandler);
			}
			
		}
		
		/**
		 * 隐藏进度条
		 */
		public function hide() : void
		{
			PopUpManager.removePopUp(this);
		}
		
		/**
		 * 设置监听的组件组
		 */
		public function set sources(value:Array) : void
		{
			_sources = new ArrayCollection(value);
			
			for each (var element:* in _sources) {
				element.addEventListener(RPCEvent.DATA_PARSE_COMPLETED, listen);
			}
			
		}
		
		/**
		 * 保持居中显示
		 */
		private function resizeHandler(event:ResizeEvent) : void 
		{
			this.x = app.width/2 - this.width/2;
			this.y = app.height/2 - this.height/2;
		}
		
		/**
		 * 当有组件触发DATA_PARSE_COMPLETED事件时，执行这个方法，判断是否所有组件完成数据解析
		 */
		private function listen(event:RPCEvent) : void
		{
			var target = event.target;
			
			_sources.removeItemAt(_sources.getItemIndex(target));
			
			if(_sources == null || _sources.length == 0) {
				//触发加载完成事件，便于设置界面上控件的初始化值
				var e:Event = new Event("LOAD_COMPLATE");
				this.dispatchEvent(e);
				hide();
			}
		}
	}
}